package com.jiuyun.filter;

import com.mysql.cj.Session;

import javax.servlet.*;
import javax.servlet.annotation.*;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebFilter("/admin/*")
public class HelloFilter implements Filter {
    //执行过滤 参数三个 请求、响应、过滤器链
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        System.out.println("hello 正在过滤。。。");
        chain.doFilter(req, resp);
        HttpServletResponse response=(HttpServletResponse)resp;
        HttpServletRequest request=(HttpServletRequest)req;
        HttpSession session=request.getSession();
        String servletPath = request.getServletPath();
        String path = request.getRequestURI().toString();
        String a=path.substring(path.lastIndexOf("/")+1);
        String b=path.substring(path.lastIndexOf("/admin")+1);
        String c=b.substring(0,5);
        System.out.println("我是"+c);
        //取出请求参数
        String name = (String) session.getAttribute("stname");
        String pass = (String) session.getAttribute("stpass");
        System.out.println("我是"+name+"+"+pass);
        //req.getSession();
            if("admin".equals(name) && "123".equals(pass) || "login.jsp".equals(a) || "admin".equals(c)){
                chain.doFilter(req, resp);//进入下一个过滤器,进入资源
            }else{
                //跳转页面
                response.sendRedirect("/login.jsp");
            }
    }
    public void init(FilterConfig config) throws ServletException {
        System.out.println("hello 初始化");
    }
    public void destroy() {
        System.out.println("hello 销毁");
    }

}
